import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
// 1.创建axios实例
const service = axios.create({
  // 基地址（axios区分不同环境地址）
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
service.interceptors.request.use(config => {
  // 注入token
  const storedToken = store.getters.token
  if (storedToken) {
    config.headers['Authorization'] = `Bearer ${storedToken}`
  }
  return config
}, err => {
  return Promise.reject(err)
})
service.interceptors.response.use(response => {
  const { data, message, success } = response.data
  if (success) {
    Message({ type: 'success', message })
    return data
  } else {
    Message({ type: 'error', message })
    return Promise.reject(new Error(message))
  }
}, async(error) => {
  // 对token失效问题进行处理
  if (error.response.status === 401) {
    await store.dispatch('user/logout')
    router.push('/login')
    Message({ type: 'info', message: '身份过期,请重新登录' })
    return Promise.reject(error)
  }
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})
export default service
